// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
// 路由管理
import router from './router'
// 状态管理
import store from './vuex/store';
// ajax
import ajax from './utils/ajax';
// elemnet
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// 引入icon
import './assets/icon/iconfont.css';
Vue.use(ElementUI);

Vue.use(ajax);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>',
    data: {
        // 空的实例放到根组件下，所有的子组件都能调用
        Bus: new Vue()
    }
})


// 路由拦截器
router.beforeEach((to, from, next) => {
  if (to.matched.length !== 0) {
      if (to.meta.requireAuth) {
          if (store.state.token !== null) { // 通过state判断当前用户是否登录
              if (to.meta.permission == null || store.state.permissions.includes(to.meta.permission)) {
                next();
              }else{
                next({
                  path: '/home/dashboard',  // 如果没有权限，跳转到首页
                  query: {}
                });
              }
          } else {
              next({
                  path: '/',
                  query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
              });
          }
      } else {
          next();
      }
  } else {
      next({
          path: '/',
          query: { redirect: to.fullPath }
      })
  }
})
